//
//  AppDelegate.m
//  dangdang
//
//  Created by air on 15/12/7.
//  Copyright © 2015年 luweijie. All rights reserved.
//

#import "AppDelegate.h"
#import "APIKey.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapNaviKit/AMapNaviKit.h>
#import <AMapNaviKit/MAMapKit.h>
#import "UMessage.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "HomepageViewController.h"
#import "PrologueViewController.h"
#import "KMPayTool.h"

registerObject *userRegister = nil;
UserInfo *userObject = nil;
CityObject *cityObject = nil;

@interface AppDelegate ()<AMapLocationManagerDelegate, UIScrollViewDelegate>

{
    AMapLocationManager * _mapLocationManager;
}
@property (nonatomic, strong) UIScrollView * scr;

@end

@implementation AppDelegate

- (void)configureAPIKey
{
    //配置用户Key
    [AMapLocationServices sharedServices].apiKey = (NSString *)APIKey;
    [AMapSearchServices sharedServices].apiKey = (NSString *)APIKey;
    [AMapNaviServices sharedServices].apiKey = (NSString *)APIKey;
    [MAMapServices sharedServices].apiKey = (NSString *)APIKey;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [self configureAPIKey];
    
    [[UINavigationBar appearance] setBarTintColor:UIColorFromRGB];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                                                           [UIColor whiteColor], NSForegroundColorAttributeName,
                                                           [UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:19.0], NSFontAttributeName, nil]];
    [[UINavigationBar appearance] setBackIndicatorImage:[UIImage imageNamed:@"hk_back_white@2x.png"]];
    [[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:[UIImage imageNamed:@"hk_back_white@2x.png"]];
    
//    UIRemoteNotificationType types =
//    (UIRemoteNotificationTypeBadge
//     |UIRemoteNotificationTypeSound
//     |UIRemoteNotificationTypeAlert);
//    
//    [[UIApplication sharedApplication]registerForRemoteNotificationTypes:types];
    if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
    {
        // iOS 8 Notifications
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        
        [application registerForRemoteNotifications];
    }
    
    userRegister = [[registerObject alloc] init];
    userObject = [[UserInfo alloc] init];
    cityObject = [[CityObject alloc] init];
    
    [self obtainID];
    
    //友盟推送
    [UMessage setLogEnabled:NO];
    [UMessage startWithAppkey:@"56cbcc78e0f55a15590000d4" launchOptions:launchOptions];
    [self registerRemoteNotification];
    [UMessage setAutoAlert:NO];
    
    //微信支付
    [WXApi registerApp:@"wx5b4efab0f22cf048" withDescription:@"susong"];
    
    
//    _mapLocationManager = [[AMapLocationManager alloc] init];
//    
//    [_mapLocationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
//    
//    [_mapLocationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
//        
//        if (error)
//        {
//            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
//            
//            if (error.code == AMapLocationErrorLocateFailed)
//            {
//                return;
//            }
//        }
//        
//        //        NSLog(@"location:%@", location);
//        if (regeocode)
//        {
//            cityObject.city = regeocode.city;
//        }
//    }];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = [[UIViewController alloc]init];
    
    //在沙盒做一个文件，判断沙盒有没有这个文件
    NSString * plistPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"prologue.plist"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath] == YES){
        [self gotoMain];
    }else{
        [self makeLaunchView];
    }
    
    [self.window makeKeyAndVisible];
    
    return YES;
}

//假引导页面
-(void)makeLaunchView{
    PrologueViewController * pro = [[PrologueViewController alloc] init];
    self.window.rootViewController = pro;
}

//去主页
-(void)gotoMain{
    UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"HomepageViewController"]];
    self.window.rootViewController = navi;
}

- (void)registerRemoteNotification
{
    if([[[UIDevice currentDevice] systemVersion]floatValue]>=8)
    {
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
        {
            UIUserNotificationSettings *uns = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:nil];
            //[[UIApplication sharedApplication] registerForRemoteNotifications];
            [UMessage registerRemoteNotificationAndUserNotificationSettings:uns];
        }
        else
        {
            UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge);
            [UMessage registerForRemoteNotificationTypes:apn_type];
        }
    }
    else
    {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge);
        [UMessage registerForRemoteNotificationTypes:apn_type];
    }
}

- (void)obtainID{
    NSString * plistPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"usersList.plist"];
//    NSLog(@"plist = %@", plistPath);
    if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath] == YES){
        NSArray * array = [[NSArray alloc] initWithContentsOfFile:plistPath];
        userObject.userID = array[0];
    }
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"DeviceToken: {%@}",(NSString *)deviceToken);
    //这里进行的操作，是将Device Token发送到服务端
    [UMessage registerDeviceToken:deviceToken];
    //绑定一下userid
    if(userObject.userID)
    {
        [UMessage addAlias:userObject.userID type:@"userId" response:^(id responseObject, NSError *error) {
            if(error)
            {
                NSLog(@"友盟绑定userId失败,userId = %@",userObject.userID);
            }
            else
                NSLog(@"友盟绑定userId成功,userId = %@",userObject.userID);
        }];
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [UMessage didReceiveRemoteNotification:userInfo];
    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
    {
        return;
    }
    
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"%@",error);
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    NSLog(@"跳转到URL schema中配置的地址-->%@",url);//跳转到URL schema中配置的地址
    [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
        NSLog(@"Alipay回调:%@",resultDic);
    }];
    
    return [WXApi handleOpenURL:url delegate:[KMPayTool sharedInstance]];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    NSLog(@"跳转到URL schema中配置的地址-->%@",url);//跳转到URL schema中配置的地址
    
    //跳转支付宝钱包进行支付，处理支付结果
    [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
        NSLog(@"result = %@",resultDic);
    }];
    
    return [WXApi handleOpenURL:url delegate:[KMPayTool sharedInstance]];
}

@end
